#include "vxcommandscontroller.h"
#include "Vx.h"

ViewsMap * VxCommandsController::_views = new ViewsMap();

VxCommandsController::VxCommandsController(QGraphicsView * view) :
		 _view(view), _active(false), _spacePressed(false), _spaceCtrlPressed(false)
{
	qApp->installEventFilter(this);
}


VxCommandsController * VxCommandsController::instance(QGraphicsView * view)
{
	if (!_views->contains(view)){
		_views->insert(view, new VxCommandsController(view));
	}
	return _views->value(view);
}



bool VxCommandsController::eventFilter(QObject *obj, QEvent *event)
{

	switch(event->type()){

	case QEvent::MouseMove:{

			QMouseEvent * me = static_cast<QMouseEvent *>(event);
			if (_view->rect().contains(_view->mapFromGlobal(me->globalPos()))){
				_active = true;
				emit mouseMove(me->globalPos());
			} else {
				_active = false;
			}
			return false;
		}

	case QEvent::Wheel:{

			if (!_active){
				return false;
			}
			event->accept();

			_spaceCtrlPressed = false;

			QWheelEvent * we = static_cast<QWheelEvent *>(event);

			emit zoomByWheel(we->delta());
			emit mouseWheel(we->delta());
			return true;

		}

	case QEvent::KeyPress:{

			if (!_active){
				return false;
			}

			QKeyEvent * ke = static_cast<QKeyEvent *>(event);

			if (ke->isAutoRepeat()){
				return false;
			}


			if (ke->key() == Qt::Key_Space){

				if (ke->modifiers() == Qt::NoModifier){
					_spacePressed = true;
					event->accept();
					emit cancelAnimation();
					emit beginHandScroll();
					return true;
				}

				if (ke->modifiers() == Qt::ControlModifier){
					_spaceCtrlPressed = true;
					event->accept();
					emit cancelAnimation();
					emit zoomFitToAll();
					return true;
				}

			}
			return false;
		}

	case QEvent::KeyRelease:{


			QKeyEvent * ke = static_cast<QKeyEvent *>(event);

			if (ke->isAutoRepeat()){
				return false;
			}

			if (ke->key() == Qt::Key_Space){

				if (_spacePressed){
					_spacePressed = false;
					event->accept();
					emit endHandScroll();
					return true;
				}

				if (_spaceCtrlPressed){
					_spaceCtrlPressed = false;
					event->accept();
					emit cancelAnimation();
					emit zoomToBack();
					return true;
				}

			}
			return false;
		}


	default:;

	}

	return false;
}


